#include <iostream>
using namespace std;
#include <pthread.h>
#include <unistd.h>
/* 锁 */
pthread_mutex_t g_mutex;

void printer(const char *str)
{
    /* 加锁 */
    pthread_mutex_lock(&g_mutex);
    while (*str)
    {
        putchar(*str);
        fflush(stdout);
        str++;

        sleep(1);
    }
    /* 解锁 */
    pthread_mutex_unlock(&g_mutex);
}

/* 线程1 */
void *thread_func1(void *arg)
{
    const char *str = "hello";

    printer(str);
    pthread_exit(NULL);
}

/* 线程2 */
void *thread_func2(void *arg)
{
    const char *str = "world";
    printer(str);

    int count = 10000;
    while (count--)
    {
        cout << "l am thread_func2" << endl;
        sleep(1);
    }

    pthread_exit(NULL);
}

int main()
{
    /* 初始化锁 */
    pthread_mutex_init(&g_mutex, NULL);

    pthread_t tid1;
    pthread_create(&tid1, NULL, thread_func1, NULL);

    pthread_t tid2;
    pthread_create(&tid2, NULL, thread_func2, NULL);

    int cnt = 60;
    while (cnt--)
    {
        sleep(1);
    }
    pthread_mutex_destroy(&g_mutex);

    return 0;
}
